package servlet;

import entity.Category;
import entity.Utente;
import entity.Wish;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import session.CategoryFacadeRemote;
import session.CategoryManagerRemote;
import session.UtenteFacadeRemote;
import session.WishFacadeRemote;
import static servlet.ServletUtil.*;

/**
 * Questa classe rappresenta la servlet principale, che riceve tutte le richieste
 * http.
 *
 * @author Rachid Ouchary, Fabio Strocco, Max Passaghe, Marco Tansini.
 */
public class MainDispatcher extends HttpServlet {
    @EJB(name = "categoryManager")
    private CategoryManagerRemote categoryManager;
    @EJB
    private CategoryFacadeRemote categoryFacade;
    @EJB(name = "wishFacade")
    private WishFacadeRemote wishFacade;
    @EJB(name = "utenteFacade")
    private UtenteFacadeRemote utenteFacade;
    private static boolean init = true;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        String operation = getOperation(request);

        try {
            if(init) {
                initDB();
            }

            if(operation == null) {
                if(session == null || session.getAttribute(SESSION_UTENTE) == null) {
                    request.getRequestDispatcher("index.jsp").forward(request, response);
                } else {
                    Utente utente = utenteFacade.find((String)session.getAttribute(SESSION_UTENTE));
                    request.setAttribute("operation", ACTION_VISUALIZZA_WISHLIST);
                    request.getRequestDispatcher("MainDispatcher").forward(request, response);
                }
            } else if(operation.equals(ACTION_LOGIN) ||
                      operation.equals(ACTION_REGISTRAZIONE) ||
                      operation.equals(ACTION_LOGOUT) ||
                      operation.equals(ACTION_MODIFICA_UTENTE) ||
                      operation.equals(ACTION_GET_MODIFICA_UTENTE)) {
                request.getRequestDispatcher("GestoreLogin").
                        forward(request, response);
            } else if(operation.equals(ACTION_AGGIUNGI_AMICO) ||
                      operation.equals(ACTION_CERCA_AMICI)) {
                boolean logged =true;// requestLogin(request, response);
                if(logged)
                    request.getRequestDispatcher("GestoreAmici").
                            forward(request, response);
            } else if(operation.equals(ACTION_AGGIUNGI_DESIDERIO) ||
                      operation.equals(ACTION_CREA_DESIDERIO) ||
                      operation.equals(ACTION_MODIFICA_DESIDERIO) ||
                      operation.equals(ACTION_PRENOTA) ||
                      operation.equals(ACTION_GET_CREA_DESIDERIO)) {
                boolean logged = requestLogin(request, response);
                if(logged)
                    request.getRequestDispatcher("GestoreWishList").
                            forward(request, response);
            } else if(operation.equals(ACTION_VISUALIZZA_WISHLIST)) {
                    request.getRequestDispatcher("GestoreWishList").
                            forward(request, response);
            } else if(operation.equals(ACTION_GET_RESOURCE)) {
                request.getRequestDispatcher(request.getParameter(PARAM_RESOURCE)).
                            forward(request, response);
            } else if(operation.equals(ACTION_MESSAGE)) {
                request.getRequestDispatcher("Message.jsp").forward(request, response);
            }
        }
        finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="Metodi ausiliari">

    private boolean requestLogin(HttpServletRequest request,
                                 HttpServletResponse response)
                                           throws ServletException, IOException{
         HttpSession session = request.getSession();
         if(session.getAttribute(SESSION_UTENTE) == null) {
             //Forward login page
             request.getRequestDispatcher("index.jsp").forward(request, response);
             return false;
         }

         return true;
    }

    private void initDB() {
        categoryManager.populateCategories();
        Utente u1 = new Utente("fabio.strocco", "0000", "Fabio", "Strocco", "fabiostrocco@hotmail.it");
        Utente u2 = new Utente("marco.tansini", "1111", "Marco", "Tansini", "nonloso@hotmail.it");
        Utente u3 = new Utente("rachid.ouchary", "@@@@@@@@", "Rachid", "Ouchary", "yuveforever@hotmail.com");
        Utente u4 = new Utente("max.passaghe", "max", "Max", "Passaghe", "nonloso@hotmail.it");
        utenteFacade.create(u1);
        utenteFacade.create(u2);
        utenteFacade.create(u3);
        utenteFacade.create(u4);
        u1.aggiungiAmico(u2);
        u2.aggiungiAmico(u3);
        u3.aggiungiAmico(u4);
        utenteFacade.edit(u4);
        utenteFacade.edit(u3);
        utenteFacade.edit(u2);
        utenteFacade.edit(u1);
        List<Category> allCat = categoryFacade.findAll();
        utenteFacade.creaDesiderio(u3.getUsername(), allCat.get(1).getId(), "IPOD", 3, 2);
        utenteFacade.creaDesiderio(u3.getUsername(), allCat.get(1).getId(), "IPhone", 3, 3);
        utenteFacade.creaDesiderio(u3.getUsername(), allCat.get(2).getId(), "Mac", 1, 1);
        utenteFacade.creaDesiderio(u3.getUsername(), allCat.get(2).getId(), "IPAD", 0, 0);
        u3 = utenteFacade.find(u3.getUsername());
        boolean p = true;
        for(Wish wish : u3.getWishList()) {
            if(p) {
                wish.prenota();
                wishFacade.edit(wish);
                p = false;
            }
        }
        utenteFacade.edit(u3);

        init = false;
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }
    // </editor-fold>

}
